package controller;

import view.AdminView;
import service.VideoService;
import model.Video;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AdminController {
    private final AdminView view;
    private final VideoService videoService;

    public AdminController(AdminView view) {
        this.view = view;
        this.videoService = VideoService.getInstance();
        updateVideoList();

        // 绑定监听器
        view.addAddButtonListener(new AddButtonListener());
        view.addDeleteButtonListener(new DeleteButtonListener());
    }

    // 生成视频ID
    private String generateNewId() {
        return UUID.randomUUID().toString();
    }

    // 核心方法：添加视频逻辑
    public void handleAddVideo(String title, String filePath) {
        // 双重验证确保路径不为空
        if (filePath == null || filePath.trim().isEmpty()) {
            showErrorMessage("文件路径不能为空");
            return;
        }

        try {
            Video video = new Video(null, title, filePath); // ID设为null使用自增

            boolean success = videoService.addVideo(video);
            if (success) {
                showSuccessMessage("视频添加成功");
                updateVideoList(); // 刷新列表
            } else {
                showErrorMessage("视频添加失败");
            }
        } catch (Exception e) {
            showErrorMessage("系统错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 更新视频列表
//    private void updateVideoList() {
//        view.setVideoList(videoService.getAllVideos());
//    }

    // 在AdminController中添加/修改
    private void updateVideoList() {
        // 确保在事件分发线程执行
        SwingUtilities.invokeLater(() -> {
            DefaultListModel<Video> model = view.getVideoListModel();
            model.clear(); // 清空现有数据

            // 从数据库重新加载
            List<Video> videos = videoService.getAllVideos();
            for (Video video : videos) {
                model.addElement(video); // 逐条添加
            }

            // 触发界面重绘
            view.repaint();
            System.out.println("已刷新列表，当前视频数: " + model.getSize()); // 调试日志
        });
    }

    // 显示成功消息
    private void showSuccessMessage(String message) {
        JOptionPane.showMessageDialog(view, message, "成功", JOptionPane.INFORMATION_MESSAGE);
    }

    // 显示错误消息
    private void showErrorMessage(String message) {
        JOptionPane.showMessageDialog(view, message, "错误", JOptionPane.ERROR_MESSAGE);
    }

    // 显示警告消息
    private void showWarningMessage(String message) {
        JOptionPane.showMessageDialog(view, message, "警告", JOptionPane.WARNING_MESSAGE);
    }

    // 添加视频的监听器
    private class AddButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // 1. 禁用Windows文件选择器警告
            System.setProperty("sun.awt.shell.win32.fileDialogWarning", "false");

            // 2. 输入视频标题
            String title = JOptionPane.showInputDialog(view, "请输入视频标题:", "添加视频", JOptionPane.PLAIN_MESSAGE);
            if (title == null || title.trim().isEmpty()) {
                showWarningMessage("视频标题不能为空");
                return;
            }
            title = title.trim();

            // 3. 选择视频文件（增强健壮性）
            JFileChooser fileChooser = new JFileChooser();
            // 设置文件过滤器，仅显示mp4文件
            fileChooser.setFileFilter(new FileNameExtensionFilter("MP4视频文件", "mp4"));

            int returnValue = fileChooser.showOpenDialog(view);
            if (returnValue != JFileChooser.APPROVE_OPTION) {
                return; // 用户取消选择
            }

            File selectedFile = fileChooser.getSelectedFile();
            if (selectedFile == null) {
                showErrorMessage("未选择任何文件");
                return;
            }

            // 4. 获取并验证文件路径
            String filePath;
            try {
                // 转换为项目相对路径
                filePath = "/videos/" + selectedFile.getName();

                // 验证文件扩展名
                if (!filePath.toLowerCase().endsWith(".mp4")) {
                    showErrorMessage("只支持MP4格式的视频文件");
                    return;
                }

                // 复制文件到项目目录（可选）
                Path destPath = Paths.get("src/main/resources" + filePath);
                Files.createDirectories(destPath.getParent());
                Files.copy(selectedFile.toPath(), destPath, StandardCopyOption.REPLACE_EXISTING);
            } catch (Exception ex) {
                showErrorMessage("文件处理失败: " + ex.getMessage());
                return;
            }

            // 5. 调用处理方法
            handleAddVideo(title, filePath);
        }
    }

    // 删除视频的监听器
    private class DeleteButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            Video selectedVideo = view.getSelectedVideo();
            if (selectedVideo != null) {
                int confirm = JOptionPane.showConfirmDialog(
                        view,
                        "确认删除视频 '" + selectedVideo.getTitle() + "'?",
                        "警告",
                        JOptionPane.YES_NO_OPTION
                );
                if (confirm == JOptionPane.YES_OPTION) {
                    videoService.deleteVideo(selectedVideo.getId());
                    updateVideoList();
                }
            }
        }
    }
}